<template>
  <div class="add-question-page">
    <h2 class="page-title">设置题目内容</h2>
    <a-form
        :model="questionContent"
        class="question-form"
        label-align="left"
        auto-label-width
        @submit="handleSubmit"
    >
      <a-form-item label="app名称">{{props.appName}}</a-form-item>

      <a-form-item label="题目列表" :content-flex="false" :merge-props="false">
        <a-space direction="vertical" size="large" fill>
          <div class="action-bar">
            <a-button
                type="primary"
                @click="addQuestion(questionContent.length)"
            >
              <template #icon>
                <icon-plus/>
              </template>
              底部添加题目
            </a-button>
          </div>

          <!-- 遍历每道题目 -->
          <div
              v-for="(question, index) in questionContent"
              :key="index"
              class="question-card"
          >
            <div class="question-header">
              <h3 class="question-title">题目 {{ index + 1 }}</h3>
              <a-space>
                <a-button
                    type="outline"
                    size="small"
                    @click="toggleQuestionCollapse(index)"
                >
                  <template #icon>
                    <icon-up v-if="!isQuestionCollapsed(index)"/>
                    <icon-down v-else/>
                  </template>
                  {{ isQuestionCollapsed(index) ? '展开' : '折叠' }}
                </a-button>
                <a-button
                    type="outline"
                    size="small"
                    @click="addQuestion(index + 1)"
                >
                  <template #icon>
                    <icon-plus/>
                  </template>
                  添加题目
                </a-button>
                <a-button
                    size="small"
                    status="danger"
                    @click="deleteQuestion(index)"
                >
                  <template #icon>
                    <icon-delete/>
                  </template>
                  删除题目
                </a-button>
              </a-space>
            </div>

            <a-form-item :label="`题目 ${index + 1} 标题`">
              <a-input
                  v-model="question.title"
                  placeholder="请输入标题"
                  allow-clear
              />
            </a-form-item>

            <!-- 题目选项 -->
            <div class="options-section" v-if="!isQuestionCollapsed(index)">
              <div class="options-header">
                <h4 class="options-title">题目 {{ index + 1 }} 选项列表</h4>
                <a-button
                    type="outline"
                    size="small"
                    @click="addQuestionOption(question, question.options.length)"
                >
                  <template #icon>
                    <icon-plus/>
                  </template>
                  底部添加选项
                </a-button>
              </div>

              <div class="options-list">
                <div
                    v-for="(option, optionIndex) in question.options"
                    :key="optionIndex"
                    class="option-item"
                >
                  <div class="option-header">
                    <span class="option-number"
                    >选项 {{ optionIndex + 1 }}</span
                    >
                    <a-space>
                      <a-button
                          size="mini"
                          type="outline"
                          @click="addQuestionOption(question, optionIndex + 1)"
                      >
                        添加选项
                      </a-button>
                      <a-button
                          size="mini"
                          status="danger"
                          @click="deleteQuestionOption(question, optionIndex)"
                      >
                        删除选项
                      </a-button>
                    </a-space>
                  </div>

                  <div class="option-content">
                    <a-grid :cols="2" :row-gap="16" :col-gap="16">
                      <a-grid-item>
                        <a-form-item label="选项 key">
                          <a-input
                              v-model="option.key"
                              placeholder="请输入选项 key"
                              allow-clear
                          />
                        </a-form-item>
                      </a-grid-item>
                      <a-grid-item>
                        <a-form-item label="选项值">
                          <a-input
                              v-model="option.value"
                              placeholder="请输入选项值"
                              allow-clear
                          />
                        </a-form-item>
                      </a-grid-item>
                      <a-grid-item>
                        <a-form-item label="选项结果">
                          <a-input
                              v-model="option.result"
                              placeholder="请输入选项结果"
                              allow-clear
                          />
                        </a-form-item>
                      </a-grid-item>
                      <a-grid-item>
                        <a-form-item label="选项得分">
                          <a-input-number
                              v-model="option.score"
                              placeholder="请输入选项得分"
                              mode="button"
                              :min="0"
                          />
                        </a-form-item>
                      </a-grid-item>
                    </a-grid>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </a-space>
      </a-form-item>

      <div class="form-footer">
        <a-button type="primary" html-type="submit" size="large">
          提交
        </a-button>
      </div>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import {defineProps, nextTick, onMounted, ref, watchEffect, withDefaults} from "vue";
import API from "@/servers/api/typings";
import {useRouter} from "vue-router";
import {
  addQuestionPost,
  edit,
  queryAll,
} from "@/servers/api/questionController";
import message from "@arco-design/web-vue/es/message";
import AiGenerateQuestionDrawer from "@/views/add/components/AiGenerateQuestionDrawer.vue";
import {useSelectApp} from "@/hooks/SelectApp";

const router = useRouter();
const {appIdNamList, appSelectValue} = useSelectApp();

//定义属性
interface Props {
  appId: number;
  appName:string;
}

// 每个题目的折叠状态
const questionCollapsedStates = ref<boolean[]>([]);

/**
 * 切换题目折叠状态
 * @param index 题目索引
 */
const toggleQuestionCollapse = (index: number) => {
  // 确保数组长度足够
  if (questionCollapsedStates.value.length <= index) {
    questionCollapsedStates.value = [...questionCollapsedStates.value, ...Array(index - questionCollapsedStates.value.length + 1).fill(false)];
  }
  questionCollapsedStates.value[index] = !questionCollapsedStates.value[index];
};

/**
 * 判断题目是否折叠
 * @param index 题目索引
 * @returns 是否折叠
 */
const isQuestionCollapsed = (index: number): boolean => {
  return questionCollapsedStates.value[index] || false;
};

/**
 * 滚动到指定题目
 * @param index 题目索引
 */
const scrollToQuestion = (index: number) => {
  const questionElements = document.querySelectorAll('.question-card');
  if (questionElements[index]) {
    questionElements[index].scrollIntoView({
      behavior: 'smooth',
      block: 'nearest'
    });
  }
};

const props = defineProps<Props>();

//回显数据
onMounted(() => {
  appSelectValue.value = 2;
});

// 题目内容结构（理解为题目列表）
const questionContent = ref<API.questionContentDTO[]>([]);

/**
 * 添加题目
 * @param index
 */
const addQuestion = (index: number) => {
  questionContent.value.splice(index, 0, {
    title: "",
    options: [],
  });
  // 在对应位置插入折叠状态（默认展开）
  questionCollapsedStates.value.splice(index, 0, false);

  // 等待DOM更新后滚动到新添加的题目
  nextTick(() => {
    scrollToQuestion(index);
  });
};

/**
 * 删除题目
 * @param index
 */
const deleteQuestion = (index: number) => {
  questionContent.value.splice(index, 1);
  // 同时删除对应的折叠状态
  questionCollapsedStates.value.splice(index, 1);
};

/**
 * 添加题目选项
 * @param question
 * @param index
 */
const addQuestionOption = (question: API.questionContentDTO, index: number) => {
  if (!question.options) {
    question.options = [];
  }
  question.options.splice(index, 0, {
    key: "",
    value: "",
  });
};

/**
 * 删除题目选项
 * @param question
 * @param index
 */
const deleteQuestionOption = (
    question: API.questionContentDTO,
    index: number
) => {
  if (!question.options) {
    question.options = [];
  }
  question.options.splice(index, 1);
};

const oldQuestion = ref<API.QuestionVo>();

/**
 * 加载数据
 */
const loadData = async () => {
  if (!props.appId) {
    return;
  }
  const res = await queryAll({
    appId: props.appId,
    current: 1,
    size: 1,
    // sortField: "createTime",
    // sortOrder: "descend",
  });
  if (res.data.code === 0 && res.data.data?.records) {
    oldQuestion.value = res.data.data?.records[0];
    if (oldQuestion.value != null) {
      questionContent.value = oldQuestion.value.questionContentDTO ?? [];
      // 初始化折叠状态数组（默认全部展开）
      questionCollapsedStates.value = Array(questionContent.value.length).fill(false);
    }
  } else {
    message.error("获取数据失败，" + res.data.message);
  }
};

// 获取旧数据
watchEffect(() => {
  loadData();
});

/**
 * 提交
 */
const handleSubmit = async () => {
  if (!props.appId || !questionContent.value) {
    return;
  }
  let res: any;
  // 如果是修改
  if (oldQuestion.value?.id) {
    res = await edit({
      id: oldQuestion.value.id,
      questionContent: questionContent.value,
    });
  } else {
    // 创建
    res = await addQuestionPost({
      appId: props.appId as any,
      questionContent: questionContent.value,
    });
  }
  if (res.data.code === 0) {
    message.success("操作成功，即将跳转到应用详情页");
    setTimeout(() => {
      router.push(`/app/detail/${props.appId}`);
    }, 3000);
  } else {
    message.error("操作失败，" + res.data.message);
  }
};

/**
 * AI 生成题目成功后执行
 */
const onAiGenerateSuccess = (result: API.questionContentDTO[]) => {
  message.success(`AI 生成题目成功，生成 ${result.length} 道题目`);
  questionContent.value = [...questionContent.value, ...result];
};

/**
 * AI 生成题目成功后执行（SSE）
 */
const onAiGenerateSuccessSSE = (result: API.questionContentDTO) => {
  questionContent.value = [...questionContent.value, result];
};

/**
 * SSE 开始生成
 * @param event
 */
const onSSEStart = (event: any) => {
  message.success("开始生成");
};

/**
 * SSE 生成完毕
 * @param event
 */
const onSSEClose = (event: any) => {
  message.success("生成完毕");
};
</script>

<style scoped lang="css">
.add-question-page {
  min-height: 100vh;
  padding: 24px;
  background: var(--color-bg-2);

  .page-title {
    margin-bottom: 32px;
    color: var(--color-text-1);
    font-weight: 500;
  }

  .question-form {
    max-width: 1200px;
    margin: 0 auto;
  }

  .app-select {
    width: 240px;
  }

  .action-bar {
    margin-bottom: 16px;
  }

  .question-card {
    margin-bottom: 24px;
    padding: 24px;
    background: var(--color-bg-1);
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    .question-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 24px;

      .question-title {
        margin: 0;
        color: var(--color-text-1);
        font-weight: 500;
      }
    }
  }

  .options-section {
    margin-top: 16px;
    padding: 16px;
    background: var(--color-fill-2);
    border-radius: 4px;

    .options-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;

      .options-title {
        margin: 0;
        color: var(--color-text-1);
        font-weight: 500;
      }
    }

    .option-item {
      margin-bottom: 16px;
      padding: 16px;
      background: var(--color-bg-1);
      border-radius: 4px;

      &:last-child {
        margin-bottom: 0;
      }

      .option-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16px;

        .option-number {
          color: var(--color-text-1);
          font-weight: 500;
        }
      }

      .option-content {
        padding: 16px;
        background: var(--color-fill-1);
        border-radius: 4px;
      }
    }
  }

  .form-footer {
    margin-top: 32px;
    text-align: center;
  }
}
</style>
